package com.lean.android.ad.core.splash


import android.os.Build
import android.os.Bundle
import androidx.activity.addCallback
import androidx.activity.viewModels
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.lean.android.ad.core.Ad
import com.lean.android.ad.core.AdLoaders
import com.lean.android.ad.core.AdSdk
import com.lean.android.ad.core.PrivacyDialogBlockChain
import com.lean.android.ad.repository.localcache.AdLocalCache
import com.lean.android.ad.utils.StatusBarHelper
import com.lean.android.ad.utils.UmengHelper
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference
import kotlin.system.exitProcess

abstract class SplashAdLauncherActivity : FragmentActivity(), IColdSplash {

    private val splashAdViewModel by viewModels<SplashAdViewModel>()
    private lateinit var splashAdView: SplashAdView
    private var splashAdRef = WeakReference<Ad>(null)

    override fun onCreate(savedInstanceState: Bundle?) {
        com.lean.android.ad.utils.StatusBarHelper.translucent(this) //沉浸式
        super.onCreate(savedInstanceState)

        onBackPressedDispatcher.addCallback { }

        splashAdView = AdSdk.getAdConfig().splashAdView
        setContentView(splashAdView.createContentView(this))

        splashAdView.startProgressAnimation()

        collectFlow()
    }

    private fun collectFlow() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.CREATED) {
                launch {
                    splashAdViewModel.adInitState.collectLatest {
                        if (it is AdSdk.AdInitState.BlockedByPrivacyDialog) {
                            showPrivacyDialog(object : PrivacyDialogBlockChain {
                                override fun onAccept(afterCall: () -> Unit) {
                                    AdLocalCache.isPrivacyAgree = true
                                    afterCall()
                                }

                                override fun onDenied() {
                                    exitProcess(0) //结束进程
                                }
                            })
                        } else if (it is AdSdk.AdInitState.Success) {//等待SDK初始化成功
                            UmengHelper.onEvent(this@SplashAdLauncherActivity, "launch_splash")
                            loadSplashAd()
                        }
                    }
                }

            }
        }
    }

    private fun isLastSplashAd() = splashAdViewModel.currentSplashAdCount == getSplashAdCount() - 1

    private fun loadSplashAd() {
        if (splashAdViewModel.currentSplashAdCount >= getSplashAdCount()) {
            onSplashAdFinished()
            return
        }
        //加载冷开屏广告
        val container = splashAdView.findSplashContainer()
        AdLoaders.startSplashAd(this, container, true, onAdLoaded = { ad ->
            splashAdRef = WeakReference(ad)
            AdSdk.splashAdManager.updateSplashAdState(
                SplashAdState.LoadSuccess(
                    ad
                )
            )
        }, onAdShow = {
            AdSdk.splashAdManager.updateSplashAdState(SplashAdState.Shown)
            AdLocalCache.splashAdShowTime = System.currentTimeMillis()

            if (isLastSplashAd()) {
                AdLoaders.preloadInterstitialAd(this@SplashAdLauncherActivity)
                splashAdView.cancelProgressAnimation()
            }

        }, onAdFinished = {
            splashAdRef.get()?.also { ad ->
                ad.destroy()
            }
            splashAdRef.clear()

            splashAdViewModel.currentSplashAdCount += 1

            loadSplashAd()
        })
    }

    private fun onSplashAdFinished() {
        AdSdk.splashAdManager.close()
        launchMain()

        finish()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            overrideActivityTransition(
                OVERRIDE_TRANSITION_OPEN, android.R.anim.fade_in, android.R.anim.fade_out
            )
        } else {
            overridePendingTransition(
                android.R.anim.fade_in, android.R.anim.fade_out
            )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        AdSdk.splashAdManager.close()
        splashAdRef.get()?.also { ad ->
            ad.destroy()
        }
        splashAdRef.clear()
    }

    abstract fun launchMain()

    abstract fun showPrivacyDialog(chain: PrivacyDialogBlockChain)

    protected open fun getSplashAdCount(): Int = 1
}